package com.yunxin.core.admin.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.core.admin.domain.AdminTeam;
import com.yunxin.core.admin.domain.AdminUserTeamShip;
import com.yunxin.core.admin.service.AdminTeamService;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import com.yunxin.core.admin.mapper.AdminUserTeamShipMapper;
import com.yunxin.core.domain.external.merchant.MerchantExternalService;
import com.yunxin.core.domain.model.merchant.MerchantInfo;
import com.yunxin.core.domain.model.merchant.MerchantInfoRepository;
import com.yunxin.core.domain.model.team.UserTeamShip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【sys_user_team_ship(商户用户团队关系表)】的数据库操作Service实现
* @createDate 2024-05-23 19:02:08
*/
@DS("admin")
@Service
public class AdminUserTeamShipServiceImpl extends ServiceImpl<AdminUserTeamShipMapper, AdminUserTeamShip>
    implements AdminUserTeamShipService{

    @Autowired
    private AdminTeamService adminTeamService;
    @Autowired
    private MerchantInfoRepository merchantInfoRepository;
    @Autowired
    private MerchantExternalService merchantExternalService;

    @Override
    public void updateReceivingStatusByTeamId(List<Integer> teamIds) {
        LambdaUpdateWrapper<AdminUserTeamShip> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.in(AdminUserTeamShip::getTeamId,teamIds)
                .set(AdminUserTeamShip::getReceivingStatus,0);
        //判断该商户下的所有话务员是否关闭 关闭 商户接单也关闭
        List<AdminTeam> adminTeams = adminTeamService.listByIds(teamIds);
        Set<Integer> merchantIds = adminTeams.stream().map(i -> i.getMerchantId()).collect(Collectors.toSet());
        for (Integer merchantId : merchantIds) {
            //如果是关闭接单状态 判断该商户下的话务员是否全部关闭  是的话关闭要的商户接单状态
            List<UserTeamShip> userTeamShips = merchantExternalService.listReceivingStatusByMerchantId(merchantId.longValue(), "BOKE_TELEPHONE");
            if (userTeamShips.isEmpty()){
                MerchantInfo merchantInfo = new MerchantInfo();
                merchantInfo.setId(merchantId.longValue());
                merchantInfo.setType(0);
                boolean result = merchantInfoRepository.updateMerchantInfo(merchantInfo);
            }
        }

        this.update(updateWrapper);
    }

    @Override
    public List<AdminUserTeamShip> getListByUserId(Integer userId) {
        LambdaQueryWrapper<AdminUserTeamShip> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserTeamShip::getUserMerchantId,userId);
        return this.list(queryWrapper);
    }
}




